package cn.mugutu.finance.service.system.impl;

import cn.mugutu.finance.annotation.SysResource;
import cn.mugutu.finance.domain.system.Department;
import cn.mugutu.finance.domain.system.DictionaryDetail;
import cn.mugutu.finance.domain.system.DictionaryType;
import cn.mugutu.finance.domain.system.Menu;
import cn.mugutu.finance.domain.system.Resource;
import cn.mugutu.finance.domain.system.Role;
import cn.mugutu.finance.domain.system.SystemConfig;
import cn.mugutu.finance.domain.system.User;
import cn.mugutu.finance.service.system.DepartmentService;
import cn.mugutu.finance.service.system.DictionaryDetailService;
import cn.mugutu.finance.service.system.DictionaryTypeService;
import cn.mugutu.finance.service.system.InitService;
import cn.mugutu.finance.service.system.MenuService;
import cn.mugutu.finance.service.system.ResourceService;
import cn.mugutu.finance.service.system.RoleService;
import cn.mugutu.finance.service.system.SystemConfigService;
import cn.mugutu.finance.service.system.UserService;
import cn.mugutu.finance.utils.ConstantConfig;
import cn.mugutu.finance.utils.EncryptUtil;
import cn.mugutu.finance.utils.PackageUtil;
import cn.mugutu.finance.utils.ResourcesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 系统初始化服务
 */
@Service
@Slf4j
public class InitServiceImpl implements InitService {

    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DictionaryTypeService dictionaryTypeService;
    @Autowired
    private DictionaryDetailService dictionaryDetailService;

    @Override
    public void initSysBaseData() {
        initResource();
        initMenu();
        initRole();
        initDepartment();
        initUser();
        initSysVersion();
        initSystemDictionaryData();
    }

    /**
     * 初始化系统资源
     */
    public void initResource() {
        Set<Class<?>> rclazz = PackageUtil.scanClassesByPackage("cn.mugutu.finance.controller");
        for (Class<?> clazz : rclazz) {
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(SysResource.class)) {
                    SysResource sr = method.getAnnotation(SysResource.class);

                    Resource rs = resourceService.findByCode(sr.code());
                    if (rs == null) {
                        Resource resource = new Resource();
                        resource.setName(sr.name());
                        resource.setCode(sr.code());
                        resourceService.save(resource);
                    }
                }
            }

        }

        log.info("===系统资源初始化完毕....");
    }

    /**
     * 初始化系统菜单
     */
    public void initMenu() {

        List<Menu> list = menuService.findAll();
        if (list.size() == 0) {

            //======一级菜单 start=====

            Menu cwgl = new Menu();
            cwgl.setId(1L);
            cwgl.setName("财务管理");
            cwgl.setIcon("database_refresh");
            menuService.save(cwgl);

            Menu xtgl = new Menu();
            xtgl.setId(2L);
            xtgl.setName("系统管理");
            xtgl.setIcon("plugin");
            menuService.save(xtgl);

            //======一级菜单 end=====

            //======二级菜单 start=====
            //			Menu cdgl = new Menu();
            //			cdgl.setId(10L);
            //			cdgl.setName("菜单管理");
            //			cdgl.setUrl("menu/listUI");
            //			cdgl.setIcon("hammer_screwdriver");
            //			cdgl.setParent(xtgl);  				//父级是系统管理
            //			menuService.save(cdgl);

            Menu zygl = new Menu();
            zygl.setId(11L);
            zygl.setName("系统资源");
            zygl.setUrl("resource/listUI");
            zygl.setIcon("2012080404391");
            zygl.setParent(xtgl);               //父级是系统管理
            menuService.save(zygl);

            Menu bmgl = new Menu();
            bmgl.setId(12L);
            bmgl.setName("部门管理");
            bmgl.setUrl("department/listUI");
            bmgl.setIcon("user_home");
            bmgl.setParent(xtgl);                //父级是系统管理
            menuService.save(bmgl);

            Menu yggl = new Menu();
            yggl.setId(13L);
            yggl.setName("用户管理");
            yggl.setUrl("user/listUI");
            yggl.setIcon("03");
            yggl.setParent(xtgl);                //父级是系统管理
            menuService.save(yggl);

            Menu jsgl = new Menu();
            jsgl.setId(14L);
            jsgl.setName("角色管理");
            jsgl.setUrl("role/listUI");
            jsgl.setIcon("1012333");
            jsgl.setParent(xtgl);               //父级是系统管理
            menuService.save(jsgl);

            Menu zdlxgl = new Menu();
            zdlxgl.setId(15L);
            zdlxgl.setName("数据字典");
            zdlxgl.setUrl("dictionaryType/listUI");
            zdlxgl.setIcon("database_gear");
            zdlxgl.setParent(xtgl);              //父级是系统管理
            menuService.save(zdlxgl);

            Menu zdxqgl = new Menu();
            zdxqgl.setId(16L);
            zdxqgl.setName("字典详情");
            zdxqgl.setUrl("dictionaryDetail/listUI");
            zdxqgl.setIcon("database_copy");
            zdxqgl.setParent(xtgl);              //父级是系统管理
            menuService.save(zdxqgl);

            Menu xtrzgl = new Menu();
            xtrzgl.setId(17L);
            xtrzgl.setName("系统日志");
            xtrzgl.setUrl("log/listUI");
            xtrzgl.setIcon("bug");
            xtrzgl.setParent(xtgl);              //父级是系统管理
            menuService.save(xtrzgl);

            Menu druidsjygl = new Menu();
            druidsjygl.setId(18L);
            druidsjygl.setName("Jdbc监控");
            druidsjygl.setUrl("druid/index.html");
            druidsjygl.setIcon("server_database");
            druidsjygl.setParent(xtgl);              //父级是系统管理
            menuService.save(druidsjygl);

            Menu cwbbgl = new Menu();
            cwbbgl.setId(19L);
            cwbbgl.setName("双色球");
            cwbbgl.setUrl("doubleball/listUI");
            cwbbgl.setIcon("piechart");
            cwbbgl.setParent(cwgl);              //父级是财务管理
            menuService.save(cwbbgl);

            Menu cwzmt = new Menu();
            cwzmt.setId(20L);
            cwzmt.setName("百家本地");
            cwzmt.setUrl("baijia/listUI");
            cwzmt.setIcon("databases");
            cwzmt.setParent(cwgl);              //父级是财务管理
            menuService.save(cwzmt);

        }

        log.info("===系统菜单初始化完毕....");
        //======二级菜单 end=====

    }

    /**
     * 初始化系统角色
     */
    public void initRole() {

        List<Role> list = roleService.findAll();
        if (list.size() == 0) {
            Role cjgly = new Role();
            cjgly.setId(1L);
            cjgly.setName("超级管理员");
            cjgly.setResources(new HashSet<>(resourceService.findAll()));
            cjgly.setMenus(new HashSet<>(menuService.findAll()));
            cjgly.setDescription("超级管理员角色，拥有系统中所有的资源访问权限");
            roleService.save(cjgly);

            Role yhgly = new Role();
            yhgly.setId(2L);
            yhgly.setName("用户管理员");
            yhgly.setDescription("用户管理员,管理系统用户");
            List<Resource> userResources = (List<Resource>) resourceService.findByHql("FROM Resource r WHERE r.code LIKE ? ", "user:%");
            List<Menu> userMenus = (List<Menu>) menuService.findByHql("FROM Menu m WHERE m.url IS NULL OR m.url LIKE ? ", "user/%");
            yhgly.setResources(new HashSet<>(userResources));
            yhgly.setMenus(new HashSet<>(userMenus));
            roleService.save(yhgly);
        }

        log.info("===系统角色初始化完毕....");

    }

    /**
     * 初始化部门
     */
    public void initDepartment() {
        List<Department> list = departmentService.getAll();
        if (list.size() == 0) {
            Department d1 = new Department();
            d1.setId(1L);
            d1.setName("总公司");
            departmentService.save(d1);

            Department d2 = new Department();
            d2.setId(2L);
            d2.setName("管理部");
            d2.setParent(d1);
            departmentService.save(d2);

            Department d3 = new Department();
            d3.setId(3L);
            d3.setName("财务部");
            d3.setParent(d1);
            departmentService.save(d3);

            Department d4 = new Department();
            d4.setId(4L);
            d4.setName("技术部");
            d4.setParent(d1);
            departmentService.save(d4);

            log.info("===系统部门初始化完毕....");
        }
    }

    /**
     * 初始化系统用户
     */
    public void initUser() {
        List<User> list = userService.findAll();
        if (list.size() == 0) {
            Department department = departmentService.get(4L);  //技术部

            User user = new User();
            user.setId(1L);
            user.setUsername("admin");
            user.setRealname("系统管理员甘");
            user.setPassword(EncryptUtil.md5Encrypt(ConstantConfig.DEFAULT_PASSWORD));
            user.setLocked(false);
            user.setCreateDate(new Date());
            Role manageRole = roleService.get(1L);  //管理员角色
            user.getRoles().add(manageRole);
            user.setDepartment(department);
            userService.save(user);

            User user2 = new User();
            user2.setId(2L);
            user2.setUsername("ganbo");
            user2.setRealname("甘波");
            user2.setPassword(EncryptUtil.md5Encrypt(ConstantConfig.DEFAULT_PASSWORD));
            user2.setLocked(false);
            user2.setCreateDate(new Date());
            Role userManageRole = roleService.get(2L);
            user2.getRoles().add(userManageRole);
            user2.setDepartment(department);    //技术部
            userService.save(user2);

            log.info("===系统用户初始化完毕....");
        }
    }

    /**
     * 初始化系统数据字典类型和字典明细
     */
    public void initSystemDictionaryData() {

        List<DictionaryType> typeList = dictionaryTypeService.findAll();
        if (typeList.size() == 0) {
            //初始化系统数据字典类型
            List<String> dictionaryTypeKeys = ResourcesUtil.getKeyList("opot_baseData");
            for (String key : dictionaryTypeKeys) {
                if (key.startsWith("systemDictionaryType")) {
                    String sn = key.substring(key.indexOf("_") + 1);
                    String name = ResourcesUtil.getValue("opot_baseData", key);
                    DictionaryType d = new DictionaryType(sn, name);
                    dictionaryTypeService.save(d);
                }
            }

            //初始化系统字典明细
            List<String> detailList = ResourcesUtil.getKeyList("opot_baseData");
            for (String key : detailList) {
                String name = ResourcesUtil.getValue("opot_baseData", key);
                DictionaryType types = null;
                if (key.startsWith(DictionaryType.INCASE_CAUSE)) {
                    //进入办案区原因
                    types = dictionaryTypeService.findBySn(DictionaryType.INCASE_CAUSE);
                    DictionaryDetail detail = new DictionaryDetail(name, types);
                    dictionaryDetailService.save(detail);
                } else if (key.startsWith(DictionaryType.CUSTODY_METHOD)) {
                    //随身物品保管措施
                    types = dictionaryTypeService.findBySn(DictionaryType.CUSTODY_METHOD);
                    DictionaryDetail detail = new DictionaryDetail(name, types);
                    dictionaryDetailService.save(detail);
                } else if (key.startsWith(DictionaryType.ASK_ROOM)) {
                    //询问/迅问房间
                    types = dictionaryTypeService.findBySn(DictionaryType.ASK_ROOM);
                    DictionaryDetail detail = new DictionaryDetail(name, types);
                    dictionaryDetailService.save(detail);
                } else if (key.startsWith(DictionaryType.COLLECT_ITEM)) {
                    //信息采集项目
                    types = dictionaryTypeService.findBySn(DictionaryType.COLLECT_ITEM);
                    DictionaryDetail detail = new DictionaryDetail(name, types);
                    dictionaryDetailService.save(detail);
                } else if (key.startsWith(DictionaryType.CALL_POLICE_STATUS)) {
                    //报警情况
                    types = dictionaryTypeService.findBySn(DictionaryType.CALL_POLICE_STATUS);
                    DictionaryDetail detail = new DictionaryDetail(name, types);
                    dictionaryDetailService.save(detail);
                } else if (key.startsWith(DictionaryType.YESORNO)) {
                    //是否
                    types = dictionaryTypeService.findBySn(DictionaryType.YESORNO);
                    DictionaryDetail detail = new DictionaryDetail(name, types);
                    dictionaryDetailService.save(detail);
                } else if (key.startsWith(DictionaryType.END_LEAVE_CAUSE)) {
                    //最终离开原因
                    types = dictionaryTypeService.findBySn(DictionaryType.END_LEAVE_CAUSE);
                    DictionaryDetail detail = new DictionaryDetail(name, types);
                    dictionaryDetailService.save(detail);
                } else if (key.startsWith(DictionaryType.carryGoods_Handle_Status)) {
                    //随身物品处理情况
                    types = dictionaryTypeService.findBySn(DictionaryType.carryGoods_Handle_Status);
                    DictionaryDetail detail = new DictionaryDetail(name, types);
                    dictionaryDetailService.save(detail);
                }

            }

        }
        log.info("===系统数据字典初始化完毕....");
    }

    /**
     * 初始化系统版本信息
     */
    public void initSysVersion() {
        List<SystemConfig> list = systemConfigService.findAll();
        if (list.size() == 0) {
            SystemConfig systemConfig = new SystemConfig();
            systemConfig.setId(1L);
            systemConfig.setTitle("智能财务管理系统 ");
            systemConfig.setName("智能财务管理系统 ");
            systemConfig.setPublishDate(new Date());
            systemConfig.setSysVersion("v 1.0.0");
            systemConfig.setCopyright("成都牧固图科技有限公司");
            systemConfigService.save(systemConfig);
        }
        log.info("===系统版本信息初始化完毕...");
    }

}
